using Game.Networking.Server;
using UnityEngine;

namespace Game.Networking {
	public sealed class WorldEntityTransformInterpolator  {
		public float SnapDistance      = 0.1f;
		public float TeleportThreshold = 3f;

		Transform _transform;
		Vector3 _prevPos = Vector3.zero;
		Vector3 _lastPos = Vector3.zero;

		Quaternion _prevRot = Quaternion.identity;
		Quaternion _lastRot = Quaternion.identity;

		float   _interpProgress = 0f;
		float   _rotLerpProgress = 0f;
		float   _moveTime = 0.1f;

		public WorldEntityTransformInterpolator(Transform targetTransform) {
			_transform = targetTransform;
			_prevPos = _transform.position;
			_lastPos = _transform.position;

			_prevRot = _transform.rotation;
			_lastRot = _transform.rotation;

			_moveTime = ServerEntityController.NET_TICK_TIME + 0.02f;
			_interpProgress = 1.1f;
			_rotLerpProgress = 1.1f;
		}

		public void UpdatePosition(Vector3 newPos, bool teleport) {
			if ( Vector3.Distance(newPos, _lastPos) > TeleportThreshold || teleport ) {
				_prevPos = _lastPos;
				_lastPos = newPos;
				_interpProgress = 1.1f;
				_transform.position = newPos;
				return;
			}
			_prevPos = _lastPos;
			_lastPos = newPos;
			_interpProgress = 0f;
		}

		public void UpdateRotation(Quaternion newRot) {
			_prevRot = _lastRot;
			_lastRot = newRot;
			_rotLerpProgress= 0f;
		}

		public void Update(float deltaTime) {
			if ( _interpProgress < 1f ) {
				_transform.position = Vector3.Lerp(_prevPos, _lastPos, _interpProgress);
				_interpProgress += (deltaTime / _moveTime);				
			}
			if ( _rotLerpProgress< 1f ) {
				_transform.rotation = Quaternion.Lerp(_prevRot, _lastRot, _rotLerpProgress);
				_rotLerpProgress += (deltaTime / _moveTime);				
			}			
		}
	}
}
